package com.bgl.mall.aspect;

import com.bgl.mall.util.JsonUtil;
import com.google.common.collect.Maps;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.util.UrlPathHelper;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;
import java.util.Map;

/**
 * 日志切面
 * @author Bu Guoliang
 * @date 2018/03/03 23:25
 * @since 1.8
 */
@Slf4j
@Aspect
@Component
public class SysLogAspect {

    private UrlPathHelper pathHelper = new UrlPathHelper();

    @Pointcut(value = "execution(public * com.bgl.mall.controller.*.*.*(..))")
    public void webLog() {}

    @Before("webLog()")
    public void doBefore(JoinPoint joinPoint) {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        log.info("*******************请求开始*******************");

        Map<String, String> headers = Maps.newHashMap();
        Enumeration<String> names = request.getHeaderNames();
        while (names.hasMoreElements()) {
            String name = names.nextElement();
            headers.put(name, request.getHeader(name));
        }
        headers.remove("accept-charset");

        // 记录下请求内容
        log.info("URL ==> {}", pathHelper.getRequestUri(request));
        log.info("HEADERS ==> {}", headers);
        Object[] args = joinPoint.getArgs();
        if (args.length > 0) {
            for (int i = 0; i < args.length; i++) {
                log.info("REQUEST_BODY ==> {}", args[i]);
            }
        } else {
            log.info("REQUEST_BODY ==> []");
        }
    }

    @AfterReturning(returning = "ret", pointcut = "webLog()")
    @SneakyThrows
    public void doAfterReturning(Object ret) {
        if (ret != null && !(ret instanceof ResponseEntity)) {
            log.info("RESPONSE_BODY ==> {}", JsonUtil.obj2String(ret) );
            log.info("*******************请求完成*******************");
        }
    }
}
